package com.tpshion.chat.websocket;


import com.tpshion.chat.domain.model.MessageModel;
import com.tpshion.chat.domain.model.UnReadMsg;
import com.tpshion.chat.utils.JsonUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: weosocket服务类
 * @Author: tpshion
 * @Date: 2020/5/3 11:01
 * @Version: 1.0
 */
@Component
public class WebSocketServer {
    /**
     * 连接的客户端
     */
    public static ConcurrentHashMap<String, Channel> clients = new ConcurrentHashMap<>();

    /**
     * 未读消息
     */
    public static List<UnReadMsg> unReadMsgList = new ArrayList<>();

    /**
     * 当前用户id
     */
    public static ConcurrentHashMap<Channel,List<MessageModel>> userMsg = new ConcurrentHashMap<>();

    /**
     * 发送消息给具体的用户
     * @param messageModel
     * @param toUserId
     */
    public void sendToUser(MessageModel messageModel, String toUserId){
        if (clients.containsKey(toUserId)){
            clients.get(toUserId).writeAndFlush(new TextWebSocketFrame(JsonUtil.obj2String(messageModel)));
        }else{
            AtomicReference<Boolean> exist = new AtomicReference<>(false);
            unReadMsgList.forEach(item ->{
              if(item.getUserId().equals(toUserId)){
                  exist.set(true);
                  List<MessageModel> msgList = item.getMsgList();
                  msgList.add(messageModel);
              }
            });
            if (!exist.get()){
                List<MessageModel> messageModels = new ArrayList<>();
                messageModels.add(messageModel);
                unReadMsgList.add(new UnReadMsg(toUserId, messageModels));
            }
        }
    }

    /**
     * 检查客户端是否存在
     * @param userId
     * @return
     */
    public Boolean checkUserExist(String userId){
        if(clients.containsKey(userId)){
            return true;
        }else{
            return false;
        }
    }

}
